package com.socialcoco.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.socialcoco.entity.*;
import com.socialcoco.exception.myExection;
import com.socialcoco.mapper.DiaryResMapper;
import com.socialcoco.respone.BaseResponse;
import com.socialcoco.respone.ResultUtils;
import com.socialcoco.respone.resultenum;
import com.socialcoco.serviceImpl.*;
import com.socialcoco.util.Search;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.sql.Wrapper;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 赵志浩
 * @since 2022-03-17 09:16:50
 */
@Slf4j
@RestController
@RequestMapping("/socialcoco/user")
@Api(tags = "用户动态功能")
public class DiaryController {
    @Autowired
    private DiaryServiceImpl diaryService;
    @Autowired
    private DiaryResServiceImpl diaryResMapper;//自己封装的一个结果集的类
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private ILikeServiceImpl iLikeService;
    @Autowired
    private CommentServiceImpl commentService;
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private Search search;
    @GetMapping("listMyDiary/{uid}")
    @ApiOperation(value = "用户加载自己数据库的动态")
    public BaseResponse<Object> listMyDiary(@PathVariable int uid,@RequestHeader("token")String token){
        List<DiaryRespone> diaryRespones = diaryResMapper.listMyDiary(uid);
        log.info(String.valueOf(diaryRespones));
        DiaryRespone diaryRespone = new DiaryRespone();
        diaryRespones.add(diaryRespone);
        return ResultUtils.success(diaryRespones);
    }
    @GetMapping("listDiary/{uid}")
    @ApiOperation(value = "用户加载所有数据库的动态")
    public BaseResponse<Object> listDiary(@PathVariable int uid,@RequestHeader("token")String token) throws IOException {
        if(uid<0){
            throw new myExection(resultenum.NOPAR.getCode(),resultenum.NOPAR.getMsg());
        }

        List<DiaryRespone> diaryRespones = diaryResMapper.listDiary();

       //这里由于主页显示的消息过多，所以直接把需要的图片，动态，用户，评论，点赞，全部查询出来返回到前端
        for (int i = 0; i < diaryRespones.size(); i++) {
            QueryWrapper<Comment> CommentNum=new QueryWrapper<>();
            CommentNum.eq("didss",diaryRespones.get(i).getId());
            long count1 = commentService.count(CommentNum);
            diaryRespones.get(i).setCommentNum(count1);
            QueryWrapper<ILike> queryWrapper=new QueryWrapper<>();
            QueryWrapper<ILike> queryNum=new QueryWrapper<>();
            queryNum.eq("dzid",diaryRespones.get(i).getId());
            long count = iLikeService.count(queryNum);
            diaryRespones.get(i).setLikeNum(count);
            queryWrapper.eq("dzid",diaryRespones.get(i).getId()).eq("uid",uid);
            List<ILike> list = iLikeService.list(queryWrapper);
            if(list!=null&&list.size()>0){
                diaryRespones.get(i).setILike(list.get(0));
            }
            else {
                diaryRespones.get(i).setILike(new ILike());
            }
        }
        boolean diaryrespones = search.indexExists("diaryrespones");
        if(!diaryrespones){
            search.createIndex("diaryrespones");
            BulkRequest bulkRequest=new BulkRequest();
            bulkRequest.timeout("10s");
            for (DiaryRespone diaryRespone : diaryRespones) {
                bulkRequest.add(new IndexRequest("diaryrespones")
                        .source(JSON.toJSONString(diaryRespone), XContentType.JSON));
            }
            client.bulk(bulkRequest, RequestOptions.DEFAULT);
        }
        boolean userSearch = search.indexExists("socialuser");
        if(!userSearch){
            List<User> list = userService.list();
            search.createIndex("socialuser");
            BulkRequest bulkRequest=new BulkRequest();
            bulkRequest.timeout("10s");
            for (User user : list) {
                bulkRequest.add(new IndexRequest("socialuser")
                        .source(JSON.toJSONString(user), XContentType.JSON));
            }
            client.bulk(bulkRequest, RequestOptions.DEFAULT);
        }
        return ResultUtils.success(diaryRespones);
    }
    @ApiOperation("根据动态id显示详情动态的评论和回复")
    @GetMapping("/detailComment/{did}")
    public BaseResponse<Object> detailComment(@PathVariable("did")int did,@RequestHeader("token")String token){
        if(did<0){
            throw new myExection(resultenum.NOPAR.getCode(),resultenum.NOPAR.getMsg());
        }

        List<Comment> comments = diaryResMapper.listComment(did);
        log.info(String.valueOf(comments));
        return ResultUtils.success(comments);
    }
    @ApiOperation("用户删除动态")
    @GetMapping("/deleteDiary/{did}")
    public BaseResponse<Object> slow(@PathVariable("did")int did){
        QueryWrapper<Diary> diaryQueryWrapper=new QueryWrapper<>();
        diaryQueryWrapper.eq("id",did);
        diaryService.remove(diaryQueryWrapper);
        return ResultUtils.success("deletedOk");
    }
    @GetMapping("listDy")
    @ApiOperation(value = "后台显示动态")
    public BaseResponse<Object> listDy(@PathVariable int uid){
        List<Diary> list = diaryService.list();
        return ResultUtils.success(list);
    }
}

